package refuge;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class Rikuzen {
	DocumentBuilder docbuilder = null;
	HttpClient httpclient = null;
	
	public static void main(String[] args) throws Exception{
		Rikuzen rikuzen = new Rikuzen();
		System.out.println(rikuzen.getKML("rikuzen.kml"));
	}
	
	Rikuzen(){
		DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
		try{
			docbuilder = dbfactory.newDocumentBuilder();
		}catch(Exception e){
			e.printStackTrace();
		}
		
    	httpclient = new HttpClient();  
	}
	
	public String getKML(String filename) throws Exception{
        StringBuffer result = new StringBuffer();
        
        Document doc = docbuilder.parse(new File(filename));
        Element root = doc.getDocumentElement();
        
        NodeList list = root.getElementsByTagName("Placemark");
        
        for(int i=0; i<list.getLength(); i++){
        	Element node = (Element)list.item(i);
        	
        	String name = node.getElementsByTagName("name").item(0).getTextContent();
        	
        	String desc = node.getElementsByTagName("description").item(0).getTextContent();
        	desc = desc.replaceAll("\n", "");
        	
        	String style = node.getElementsByTagName("styleUrl").item(0).getTextContent();
        	
        	String coordinates = node.getElementsByTagName("coordinates").item(0).getTextContent();
        	String[] latlng = coordinates.split(",");
        	
        	String address = getAddress(latlng[1],latlng[0]);
        	
			String row = name+","+getType(style)+","+address+","+latlng[1]+","+latlng[0].trim()+","+desc;
        	//System.out.println(row);
        	result.append(row+"\n");
        }
        return result.toString();
	}
	
	public String getAddress(String lat, String lng){
    	GetMethod httpget = null;
		String result = "";

    	try {  
    		httpget = new GetMethod("http://maps.google.com/maps/api/geocode/xml?latlng="+lat+","+lng+"&language=ja&sensor=false&region=jp");
    		httpget.getParams().setContentCharset("UTF-8");
    		
    		int statusCode = httpclient.executeMethod(httpget);  
    		
    		if (statusCode != HttpStatus.SC_OK) {  
    			System.err.println("Method failed: " + httpget.getStatusLine());  
    		}  
    		
    		Document doc = docbuilder.parse(httpget.getResponseBodyAsStream());
    		
    		String status = doc.getElementsByTagName("status").item(0).getTextContent();
    		if(status.equals("OK")){
    			result = ((Element)doc.getElementsByTagName("formatted_address").item(0)).getTextContent();
    			String[] tmpresult = result.split(",");
    			if(tmpresult[1].trim().startsWith("岩手県")){
    				result = tmpresult[1].trim();
    			}else{
    			}
    			//System.out.println(result);
    			//System.out.println(result[0]+","+result[1]);
    		}else{
    			//System.out.println(status);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	} finally {  
    		httpget.releaseConnection();  
    	}  
		return result;
    }
	
	String getType(String style){
		int stylecode = Integer.parseInt(style.substring(6));
		switch(stylecode){
			case 11: return "仮設トイレ";
			case 71: return "交通";
			case 85: return "売店";
			case 87: return "施設";
			case 99: return "消防団";
			case 105: return "飲食店";
			case 112: return "一本松";
			case 114: return "店舗";
		}
		return style;
	}

}
